package br.dcc.ufmg.persistence;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class HSQLDBConnection {

	private static Connection connection;

	private static boolean isDatabaseCreated = false;

	private HSQLDBConnection() {
	}
        
        public static void resetDatabase() {
            shutdownConnection();
            isDatabaseCreated = false;
            connection = null;
        }

	public static void inputDatabase() throws IOException {
		String[] filesDatabase = { "risk-artifacts-filter.log",
				"risk-artifacts-filter.script", "risk-artifacts-filter.properties" };
		for (String fileDatabase : filesDatabase) {
			InputStream in = ClassLoader
					.getSystemResourceAsStream(fileDatabase);
			exportFile(fileDatabase, in);
			in.close();
		}
		isDatabaseCreated = true;
	}

	private static void exportFile(String fileDatabase, InputStream in)
			throws FileNotFoundException, IOException {
		FileOutputStream out = new FileOutputStream(System.getProperty("user.home") + File.separator + fileDatabase);
		byte[] bytes = new byte[in.available()];
		in.read(bytes);
		out.write(bytes);
		out.flush();
		out.close();
	}

	public static Connection getConnection() {
		try {
			if (!isDatabaseCreated) {
				inputDatabase();
			}
			if (connection == null) {
				String url = "jdbc:hsqldb:file:"
						+ System.getProperty("user.home") + File.separator
						+ DatabasePropertiesLoader.getInstance().get("name");
				String usuario = DatabasePropertiesLoader.getInstance().get(
						"user");
				String senha = DatabasePropertiesLoader.getInstance().get(
						"pass");

				Class.forName("org.hsqldb.jdbc.JDBCDriver").newInstance();
				connection = DriverManager.getConnection(url, usuario, senha);

			}
		} catch (SQLException ex) {
			logSQLException(ex);
		} catch (Exception e) {
			System.out
					.println("Problemas ao tentar conectar com o banco de dados: "
							+ e);
		}
		return connection;
	}

	public static void shutdownConnection() {
		try {
			connection.prepareStatement("SHUTDOWN").execute();
                        connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void logSQLException(SQLException ex) {
		System.out.println("SQLException: " + ex.getMessage());
		System.out.println("SQLState: " + ex.getSQLState());
		System.out.println("VendorError: " + ex.getErrorCode());
	}

}
